package com.rykj.qxj.util;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.log4j.Log4j;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Log4j
public class SqlTemplateUtils {
    public static void main(String[] args) throws IOException {
        String sql = "";
        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDefaultEncoding("utf-8");

        StringTemplateLoader stringLoader = new StringTemplateLoader();
        String templateContent="select * from ddr where 1=1 <#if userName??&userName!=''> and userName = :userName</#if> order by id";
        stringLoader.putTemplate("myTemplate",templateContent);
        configuration.setTemplateLoader(stringLoader);

        Template template = configuration.getTemplate("myTemplate","utf-8");
        Map root = new HashMap();
        root.put("userName", "ddd");

        StringWriter writer = new StringWriter();
        try {
            template.process(root, writer);
        } catch (TemplateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static String getSqlTemplate(String sqlTemp,Map<String,Object> parms) throws Exception {
        Configuration configuration = new Configuration(Configuration.getVersion());
        configuration.setDefaultEncoding("utf-8");

        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("sqlTemp",sqlTemp);
        configuration.setTemplateLoader(stringLoader);

        Template template = configuration.getTemplate("sqlTemp","utf-8");

        StringWriter writer = new StringWriter();
        template.process(parms, writer);
        sqlTemp = writer.toString();

        log.debug("freemarker转换后的sql语句为:" + sqlTemp);
        return sqlTemp;
    }

}
